import express from 'express'
import {addSql, countSql, getResult, listSql, putSql} from '../../../util/operateSql.js';
import { arrayToTree } from '../../../util/common.js';
import { getAccount, isExistUser } from '../../../middleWare/user/index.js';
var router = express.Router();
const table1 = 'sys_menu'
const table2 = 'sys_role_menu'

/* GET users listing. */
router.get('/query', getAccount ,function(req, res, next) {

	const { role_id } = req.master
  // const sql = listSql(table1,{orderBy: 'menu_id',role_id},{operate: {'in': ['role_id']}})
	const getMenusSql = `select * from ${table2} t1 right join ${table1} t2 on t1.menu_id=t2.menu_id where t1.role_id in (${role_id}) order By t2.sort`
	// select * from sys_role_menu  t1 right join sys_menu t2 on t1.menu_id=t2.menu_id WHERE t1.role_id in (3)
  getResult(getMenusSql).then((result) => {
	
		const handleMenuMeta = result.map(e => {
			return {
				...e,
				hidden: !+e.is_show,
				meta: {title: e.menu_name,icon: e.icon || 'home',redirect: e.redirect_path}
			}
		})
		const treeData = arrayToTree(handleMenuMeta,{key: 'menu_id',parentKey: 'parent_menu_id'})
    res.json(req.app.locals.success(treeData))
  }).catch((err) => {
    res.json(req.app.locals.error(err))
  });
});

// 获取菜单树所有
router.get('/query/all', getAccount ,function(req, res, next) {

	const { role_id } = req.master
  // const sql = listSql(table1,{orderBy: 'menu_id',role_id},{operate: {'in': ['role_id']}})
	const getMenusSql = `select * from ${table1}`
  getResult(getMenusSql).then((result) => {
	console.log('result: ', result);
		const handleMenuMeta = result.map(e => {
			return {
				...e,
				hidden: !+e.is_show,
				meta: {title: e.menu_name,icon: e.icon || 'home',redirect: e.redirect}
			}
		})
		const treeData = arrayToTree(handleMenuMeta,{key: 'menu_id',parentKey: 'parent_menu_id'})
    res.json(req.app.locals.success(treeData))
  }).catch((err) => {
    res.json(req.app.locals.error(err))
  });
});

export default router;